package com.leoman.messageapi.service.impl;

import com.leoman.entity.Constant;
import com.leoman.exception.SendMessageErrorException;
import com.leoman.exception.UserNotFindException;
import com.leoman.message.dao.MessageDao;
import com.leoman.message.entity.Message;
import com.leoman.messageapi.service.MessageApiService;
import com.leoman.messageapi.vo.PostPraiseUserVo;
import com.leoman.post.dao.PostBaseDao;
import com.leoman.post.dao.PostImageDao;
import com.leoman.post.entity.PostBase;
import com.leoman.post.entity.PostImage;
import com.leoman.privateletter.dao.PrivateLetterDao;
import com.leoman.reourceapi.service.impl.ResourceApiServiceImpl;
import com.leoman.user.dao.UserInfoDao;
import com.leoman.user.entity.UserInfo;
import com.leoman.userchange.dao.UserChangeDao;
import com.leoman.userchange.entity.UserChange;
import com.leoman.utils.ImageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 消息实现接口
 * Created by 涂奕恒 on 2016/6/12.
 */
@Service
public class MessageApiServiceImpl implements MessageApiService {

    @Autowired
    private UserInfoDao userInfoDao;

    @Autowired
    private UserChangeDao userChangeDao;

    @Autowired
    private MessageDao messageDao;

    @Autowired
    private PostBaseDao postBaseDao;

    @Autowired
    private PostImageDao postImageDao;

    @Autowired
    private PrivateLetterDao privateLetterDao;

    @Override
    public Page<PostPraiseUserVo> praisePage(Long userId, Integer pageNum, Integer pageSize) {
        List<UserChange> userChangeList = userChangeDao.iFindListByParams(userId);

        for (UserChange userChange : userChangeList) {
            if (userChange.getIsRead().equals(Constant.MESSAGE_READ_STATUS_YES)) {
                continue;
            }
            userChange.setIsRead(Constant.MESSAGE_READ_STATUS_YES);
            userChangeDao.save(userChange);
        }

        int[] info = ResourceApiServiceImpl.changePageParams(pageNum, pageSize);
        final Page<UserChange> userChangePage = userChangeDao.findListByUserId(userId, Constant.USER_CHANGE_TYPE_001, new PageRequest(info[0] - 1, info[1]));
        return new Page<PostPraiseUserVo>() {
            @Override
            public int getNumber() {
                return userChangePage.getNumber();
            }

            @Override
            public int getSize() {
                return userChangePage.getSize();
            }

            @Override
            public int getTotalPages() {
                return userChangePage.getTotalPages();
            }

            @Override
            public int getNumberOfElements() {
                return userChangePage.getNumberOfElements();
            }

            @Override
            public long getTotalElements() {
                return userChangePage.getTotalElements();
            }

            @Override
            public boolean hasPreviousPage() {
                return userChangePage.hasPreviousPage();
            }

            @Override
            public boolean isFirstPage() {
                return userChangePage.isFirstPage();
            }

            @Override
            public boolean hasNextPage() {
                return userChangePage.hasNextPage();
            }

            @Override
            public boolean isLastPage() {
                return userChangePage.isLastPage();
            }

            @Override
            public Pageable nextPageable() {
                return userChangePage.nextPageable();
            }

            @Override
            public Pageable previousPageable() {
                return userChangePage.previousPageable();
            }

            @Override
            public Iterator<PostPraiseUserVo> iterator() {
                final Iterator<UserChange> userChangeIterator = userChangePage.iterator();
                return new Iterator<PostPraiseUserVo>() {
                    @Override
                    public boolean hasNext() {
                        return userChangeIterator.hasNext();
                    }

                    @Override
                    public PostPraiseUserVo next() {
                        return getPostPraiseUserVo(userChangeIterator.next());
                    }
                };
            }

            @Override
            public List<PostPraiseUserVo> getContent() {
                List<UserChange> userChangeList = userChangePage.getContent();
                List<PostPraiseUserVo> list = new ArrayList<>();

                for (UserChange userChange : userChangeList) {
                    list.add(getPostPraiseUserVo(userChange));
                }

                return list;
            }

            @Override
            public boolean hasContent() {
                return userChangePage.hasContent();
            }

            @Override
            public Sort getSort() {
                return userChangePage.getSort();
            }
        };
    }

    private PostPraiseUserVo getPostPraiseUserVo(UserChange userChange) {
        PostPraiseUserVo postPraiseUserVo = new PostPraiseUserVo();
        postPraiseUserVo.setId(userChange.getUserInfo().getId());
        postPraiseUserVo.setNickname(userChange.getUserInfo().getNickname());
        postPraiseUserVo.setAvater(ImageUtil.clearUploadUrl(userChange.getUserInfo().getAvater()));
        postPraiseUserVo.setPostId(userChange.getPostBase().getId());
        postPraiseUserVo.setPostType(userChange.getPostBase().getType());
        if (userChange.getPostBase().getType().equals(Constant.POST_TYPE_003)) {
            List<PostImage> list = postImageDao.findList(userChange.getPostBase().getId(), userChange.getPostBase().getType());
            postPraiseUserVo.setPostCover(null != list && list.size() > 0 ? ImageUtil.clearUploadUrl(list.get(0).getSuolue()) : "");
        } else {
            postPraiseUserVo.setPostCover(ImageUtil.clearUploadUrl(userChange.getPostBase().getAvater()));
        }
        postPraiseUserVo.setPostName(userChange.getContent());
        postPraiseUserVo.setPostAuthor(userChange.getPostBase().getUserInfo().getNickname());
        postPraiseUserVo.setCreateDate(userChange.getCreateDate());

        // 将消息修改为已读状态
        // userChange.setIsRead(Constant.MESSAGE_READ_STATUS_YES);
        // userChangeDao.save(userChange);

        return postPraiseUserVo;
    }

    @Override
    @Transactional
    public Page<Message> messagePage(Long userId, Integer pageNum, Integer pageSize) throws UserNotFindException {
        int[] info = ResourceApiServiceImpl.changePageParams(pageNum, pageSize);

        if (null == userId) {
            throw new UserNotFindException();
        }

        UserInfo userInfo = userInfoDao.findOne(userId);

        if (null == userInfo) {
            throw new UserNotFindException();
        }

        String type;

        if (userInfo.getIsCreator() == 0) {
            type = "%1%";
        } else {
            type = "%2%";
        }

        // 将所有的未读通知消息设置为已读
        List<Message> messageList = messageDao.findListMessage(userId);
        for (Message message : messageList) {
            message.setIsRead(Constant.MESSAGE_READ_STATUS_YES);
            messageDao.save(message);
        }

        Page<Message> page = messageDao.pageByUserType(type, System.currentTimeMillis(), userId, new PageRequest(info[0] - 1, info[1]));
        PostBase postBase;

        for (Message message : page.getContent()) {
            if (null != message.getPostId()) {
                postBase = postBaseDao.findOne(message.getPostId());
                if (postBase.getType().equals(Constant.POST_TYPE_003)) {
                    List<PostImage> list = postImageDao.findList(postBase.getId(), postBase.getType());
                    message.setPostCover(null != list && list.size() > 0 ? ImageUtil.clearUploadUrl(list.get(0).getSuolue()) : "");
                } else {
                    message.setPostCover(ImageUtil.clearUploadUrl(postBase.getSuolue()));
                }
                message.setPostName(postBase.getName());
                message.setPostType(postBase.getType());
                message.setPostContent(postBase.getContent());
            }
            message.setContent(message.getContent().replaceAll("&lt", "<").replaceAll("&gt", ">"));

            if (!message.getTitle().contains("帖子")) {
                message.setPostId(null);
            }
        }

        return page;
    }

    @Override
    public void deleteMessage(Long messageId) throws SendMessageErrorException {
        Message message = messageDao.findOne(messageId);
        if (null == message) {
            throw new SendMessageErrorException();
        }

        if (message.getType() == 1) {
            messageDao.delete(message);
        }
    }

    @Override
    public Integer checkReadStatus(Long userId, Integer type) {
        Integer result = 0;
        // 根据type字段判断当前查询的消息类型
        switch (type) {
            case 1:
                // 回复我的
                result = messageDao.findCountPostComment(userId) + messageDao.findCountWorkComment(userId);
                break;
            case 2:
                // 点赞我的
                result = messageDao.findCountUserChange(userId);
                break;
            case 3:
                // 通知消息
                result = messageDao.findCountMessage(userId);
                break;
            case 4:
                // 私信消息
                result = privateLetterDao.findListByUserIdWithNoRead(userId).size();
                break;
        }

        return result;
    }
}
